# 一个测试策略
from IStrategy import IStrategy
from common.Order import Order


class TestStrategy(IStrategy):
    strategy_name = 'TestStrategy'
    order_sent = False
    strategy_finished = False
    deal_price = 0.0
    t_insts = []
    t_volume = {}

    def __init__(self):
        self.order_sent = False
        self.strategy_finished = False
        self.deal_price = 0.0
        self.t_insts = []
        self.t_volume = {}

    def initialize(self):
        cur_position = self.strategy_context.get_position()
        for inst in cur_position.keys():
            if inst != 'cash':
                self.t_insts += [inst]
                self.t_volume[inst] = cur_position[inst]['sellable_position']
        print('TestStrategy initialized.')

    def process_event(self, event_type, event):
        if event_type == 'MarketData':
            if self.order_sent and not self.strategy_finished and event.time > '10:15:00':
                self.send_sell_order()
                self.strategy_finished = True
            if not self.order_sent and event.time > '09:59:30':
                self.send_buy_order()
                self.order_sent = True
        elif event_type == 'OrderUpdate':
            self.strategy_context.log_message('收到成交回报: {}'.format(event))
            print(event)

    def send_buy_order(self):
        for inst in self.t_insts:
            order = Order(self.strategy_name, self.strategy_context.get_strategy_order_id(),
                          'market_order', inst, 'BUY', 0, self.t_volume[inst], 'test order')
            self.strategy_context.send_order(order)

    def send_sell_order(self):
        for inst in self.t_insts:
            order = Order(self.strategy_name, self.strategy_context.get_strategy_order_id(),
                          'market_order', inst, 'SELL', 0, self.t_volume[inst], 'test order')
            self.strategy_context.send_order(order)
